package com.csx.governance.traffic.core.support;

import com.csx.governance.traffic.core.TrafficMessageParameterExtractor;
import com.csx.governance.traffic.core.context.TrafficMessage;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * {@link TrafficMessage} 请求对象的参数解析器 执行器，顺序执行所有的解析器，将请求对象解析为一个用于进行条件匹配的Map返回
 * @author cuisongxu
 * @date 2023/4/2 16:17
 */
public class TrafficMessageParameterExtractorRunner {

    private final List<TrafficMessageParameterExtractor> trafficMessageParameterExtractors;

    public TrafficMessageParameterExtractorRunner(List<TrafficMessageParameterExtractor> trafficMessageParameterExtractors) {
        this.trafficMessageParameterExtractors = trafficMessageParameterExtractors;
    }

    public Map<String, Object> extract(TrafficMessage trafficMessage) {
        Map<String, Object> extractResult = new HashMap<>(4);
        Map<String, Object> res = new HashMap<>(16);
        for (TrafficMessageParameterExtractor parameterExtractor : trafficMessageParameterExtractors) {
            if(parameterExtractor.isSupport(trafficMessage.getClass())) {
                extractResult = parameterExtractor.extract(trafficMessage);
                res.put(parameterExtractor.parameterSource().name().toLowerCase(Locale.ROOT), extractResult);
            }
        }
        return res;
    }
}
